package com.bosssoft.cloud.wechat.infrastructure.util;

import com.bosssoft.cloud.annotations.NotNull;
import com.bosssoft.cloud.wechat.infrastructure.enums.ErrEnum;
import com.bosssoft.cloud.wechat.infrastructure.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 前端param检查类
 *
 * @author wcy create on 2021/5/17 17:24 下午
 */
@Slf4j
public class ParamUtil {

    /**
     * 校验前端Param参数是否合法
     *
     * @param <T>  T
     * @param data bean
     */
    public static <T> void checkParam(T data) {
        if (data == null) return;
        Class<?> clazz = data.getClass();
        List<Field> fields = ReflectUtil.getFieldsCallSuper(clazz);
        for (Field f : fields) {
            Annotation[] ins = f.getDeclaredAnnotations();
            for (Annotation in : ins) {
                if (in instanceof NotNull && ReflectUtil.get(data, f.getName()) == null) {
                    log.error("checkParam错误:" +
                            clazz + "的" + f.getName() + "属性不能为空！");
                    throw new BusinessException(ErrEnum.A0410, String.format("%s.%s", clazz.getSimpleName(), f.getName()));
                }
                // 可添加其他自定义校验
            }
        }
    }

}
